package other;

import java.awt.Image;

import javax.swing.ImageIcon;
import javax.swing.JPanel;

/**
 * 自定义图片Icon，可以设置图片的显示方式，如等比例缩放、填充等
 *
 * @author fdh
 */
public class MyImgIcon extends ImageIcon {
    private String imgPath;
    private JPanel parentPanel;
    private ShowType currentType;

    public enum ShowType {
        Normal, Scale, Fill
    }

    public MyImgIcon(String path, ShowType type, JPanel parent) {
        super(path);
        imgPath = path;
        parentPanel = parent;
        currentType = type;
        setShowType(type);
    }

    private void setShowType(ShowType type) {
        switch (type) {
            case Normal:
                break;
            case Scale:
                setScale();
                break;
            case Fill:
                setFill();
                break;
        }
    }

    public void changeImgSize() {
        setShowType(currentType);
    }

    /**
     * 设置为图片的等比例缩放
     */
    private void setScale() {
        double scale = Math.min(parentPanel.getWidth() * 1.0 / getIconWidth(),
                parentPanel.getHeight() * 1.0 / getIconHeight());
        Image img = getImage().getScaledInstance((int) (getIconWidth() * scale), (int) (getIconHeight() * scale),
                Image.SCALE_DEFAULT);
        setImage(img);
    }

    /**
     * 设置为图片的填充比例
     */
    private void setFill() {
        Image img = getImage().getScaledInstance(parentPanel.getWidth(), parentPanel.getHeight(), Image.SCALE_DEFAULT);
        setImage(img);
    }
}